package com.cj.webapp_Start.sp_network.encryption;

import android.os.Build;
import android.util.Base64;

import androidx.annotation.RequiresApi;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * RSA加解密
 */
public class RSAUtilsExt {

    private static final String KEY_ALGORTHM = "RSA";
    private static final int MAX_ENCRYPT_BLOCK = 117; // RSA最大加密明文大小
    private static final int MAX_DECRYPT_BLOCK = 128; // RSA最大解密密文大小
    private static final String algorithm = "RSA/ECB/PKCS1Padding";

    /**
     * 生成公钥和私钥
     *
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair genRSAKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        return keyPairGen.generateKeyPair();
    }

    /**
     * 用公钥加密
     *
     * @param data            源数据
     * @param publicKeyBase64 公钥(Base64编码)
     * @return
     * @throws Exception
     */

    public static byte[] encryptByPublicKey(byte[] data, String publicKeyBase64) throws Exception {
        // 对公钥解密
        byte[] keyBytes = Base64.decode(publicKeyBase64, Base64.NO_WRAP);
        // 取公钥
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 用私钥加密
     *
     * @param data             源数据
     * @param privateKeyBase64 公钥(Base64编码)
     * @return
     * @throws Exception
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static byte[] encryptByPrivateKey(byte[] data, String privateKeyBase64) throws Exception {
        // 对公钥解密
        byte[] keyBytes = Base64.decode(privateKeyBase64, Base64.NO_WRAP);
        // 取公钥
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

        // 对数据解密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * 用私钥解密
     *
     * @param data             已加密数据
     * @param privateKeyBase64 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, String privateKeyBase64) throws Exception {
        // 对私钥解密
        byte[] keyBytes = Base64.decode(privateKeyBase64, Base64.NO_WRAP);
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /**
     * 用公钥解密
     *
     * @param data            已加密数据
     * @param publicKeyBase64 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static byte[] decryptByPublicKey(byte[] data, String publicKeyBase64) throws Exception {
        // 对私钥解密
        byte[] keyBytes = Base64.decode(publicKeyBase64, Base64.NO_WRAP);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORTHM);
        Key publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);

        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }


//    public static void main(String[] args) throws Exception {
//        // KeyPair keyPair = genRSAKeyPair();
//        // 生成公钥和私钥
//        // RSAPublicKey publicKey = (RSAPublicKey)keyPair.getPublic();
//        // RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
//        //
//        // String publicKeyBase64 = Base64.getEncoder().encodeToString(publicKey.getEncoded());
//        // String privateKeyBase64 = Base64.getEncoder().encodeToString(privateKey.getEncoded());
//     //   System.err.println("publicKey: " + RSAUtilsExt.PUBLIC_KEY);
//        System.err.println("privateKey: " + RSAUtilsExt.PRIVATE_KEY);
//
//        String content = "1234567890123456";
//        String encryptData =
//                Base64.encodeToString(encryptByPublicKey(content.getBytes(), RSAUtilsExt.PUBLIC_KEY), Base64.NO_WRAP);
//        System.out.println("encryptData result: " + encryptData);
//        byte[] data = decryptByPrivateKey(Base64.decode(encryptData, Base64.NO_WRAP), RSAUtilsExt.PRIVATE_KEY);
//        String decryptData = new String(data);
//        System.out.println("decryptData result: " + decryptData);
//
//        String enKey = "drbcrtaqDSJVbp1fosxthQfukpnrCTtLc7fVXKljE1sjWfxEtTXs0ZoKu4FVgsqPSz/SGeGqVUm+M45HOsytVM6+fM64Np0nkvwT1pTimGa/DNSU0YmgMycUoyaAFOkNLp6kyp7/HDhWnkr+mQYv6lRCQZjZu18rTDpOrhCpc3s=";
//        byte[] aa = Base64.decode(enKey, Base64.NO_WRAP);
//        byte[] decodeByte = RSAUtilsExt.decryptByPrivateKey(aa, RSAUtilsExt.PRIVATE_KEY);
//        System.out.println("decryptData111 result: " + new String(decodeByte));
//    }

}
